package com.kpx.app.utils.datautils;

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;

import com.kpx.app.Application;
import com.kpx.app.bean.Contact;
import com.kpx.app.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * 作者： Ryan
 * 描述：
 * 创建时间：2015/3/31 16:05.
 */
public class ContactsUtils {

    private static final String[] PHONES_PROJECTION = new String[]{Phone.NUMBER, Phone.DISPLAY_NAME};

    public static final List<Contact> getContacts() {
        ContentResolver resolver = Application.instance.getContentResolver();
        List<Contact> contacts = new ArrayList<Contact>();
        Contact contact = null;
        Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.NUMBER));
                String displayName = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.DISPLAY_NAME));
                if (!StringUtil.isEmpty(phoneNumber)) {
                    phoneNumber = phoneNumber.replaceAll(" ", "");
                }
                if (!StringUtil.isEmpty(displayName)) {
                    displayName = displayName.replaceAll(" ", "");
                }
                if (!TextUtils.isEmpty(phoneNumber) && StringUtil.isValidatePhoneNumber(phoneNumber)) {
                    contact = new Contact(phoneNumber, displayName);
                    contacts.add(contact);
                } else {
                    continue;
                }
            }
            phoneCursor.close();
        }
        return contacts;
    }
}